<template>
  <div class="staffManage layout-content">
    <p>
      <a-alert
        showIcon
        type="warning"
        message="员工通过默认有效期为3个月，可点击编辑按钮进行修改员工有效期，有效期过期的员工需重新认证"
      ></a-alert>
    </p>
    <c-table
      :columns="columns"
      :data="data"
      :loading="loading"
      :add="false"
      rowKey="userId"
      @onReload="init()"
      @expanded="onExpanded"
      expanded
      :rowClassName="rowClassName"
      :scroll="{ y: '90vh' }"
    >
      <template slot="expanded" slot-scope="{ row }">
        <c-empty v-if="row.companyUserLimitDBOS.length === 0"> </c-empty>
        <c-table
          :columns="columnsExpanded"
          :data="row.companyUserLimitDBOS"
          size="small"
          :showPagination="false"
          :showHeader="false"
          v-else
        >
          <template slot="categoryCode" slot-scope="{ row }">
            {{ row.categoryName }}
          </template>
          <template slot="areas" slot-scope="{ row }">
            <c-tags :data="disposeAreas(row.areas)"></c-tags>
          </template>
          <div class="handle" slot="handle" slot-scope="{ row }">
            <c-button
              type="link"
              @click="openEditDialog(row, '0')"
              v-if="$btn('businessEdit')"
              >编辑</c-button
            >
            <a-popconfirm
              :title="`是否确认删除 ${row.categoryName} 的业务跟进？`"
              @confirm="delBusiness(row)"
            >
              <c-button type="link" v-if="$btn('businessDel')">删除</c-button>
            </a-popconfirm>
          </div>
        </c-table>
      </template>
      <template slot="roleName" slot-scope="{ row }">
        <c-tags
          :data="[row.roleName]"
          randomColor
          :colorGroup="['blue']"
        ></c-tags>
      </template>
      <template slot="validityType" slot-scope="{ row }">
        <c-tags
          :data="[validityType(row)]"
          randomColor
          :colorGroup="['orange']"
        ></c-tags>
      </template>
      <div
        class="handle"
        slot="handle"
        slot-scope="{ row }"
        v-if="
          !$isSuperAdmin(row.roleId) &&
            !isMySelf(row.userId) &&
            isActivated(row)
        "
      >
        <c-button
          type="link"
          @click="openEditDialog(row, '1')"
          v-if="$btn('staffEdit')"
          >编辑</c-button
        >
        <a-popconfirm
          :title="`是否确认删除员工${row.userName}？`"
          @confirm="delStaff(row)"
        >
          <c-button type="link" v-if="$btn('staffDel')">删除</c-button>
        </a-popconfirm>
        <c-button
          type="link"
          size="small"
          @click="openEditDialog(row, '2')"
          v-if="row.isOperateCompanyUserLimit && $btn('businessAdd')"
          >新增业务跟进</c-button
        >
      </div>
    </c-table>
    <c-modal
      v-model="visible"
      :title="modalTitle"
      destroyOnClose
      :okLoading="submitLoading"
      @ok="modalOk"
      @cancel="modalCancel"
    >
      <c-form v-model="form" ref="form" :rules="rules" :data="formData">
        <template v-slot:categoryCode>
          <span v-if="modalTitle === '编辑业务跟进'">{{
            editRow.categoryName
          }}</span>
          <c-category
            v-model="form.categoryCode"
            :filterList="categoryFilterList"
            v-else
          />
        </template>
        <template v-slot:areas>
          <c-areas v-model="form.areas" />
        </template>
      </c-form>
    </c-modal>
  </div>
</template>

<script>
import {
  getUserManagementList,
  deleteEmployee,
  updateEmployee,
  updateStaffLimit,
  addStaffLimit,
  delStaffLimit
} from "@/api/staff";
import { getRolesByCompany, getBusinessCategory } from "@/api/company";
import staff from "@/dict/staff";
import area from "@/dict/area";
import { mapState } from "vuex";
import cAreas from "@/components/areas";
import roleDict from "@/dict/role";

const tableColumns = [
  {
    title: "员工姓名",
    dataIndex: "userName",
    key: "userName"
  },
  {
    title: "手机号码",
    dataIndex: "phone",
    key: "phone"
  },
  {
    title: "员工角色",
    key: "roleName",
    scopedSlots: { customRender: "roleName" }
  },
  {
    title: "有效期",
    key: "validityType",
    scopedSlots: { customRender: "validityType" }
  },
  {
    title: "操作",
    key: "handle",
    scopedSlots: { customRender: "handle" }
  }
];
const tableColumnsExpanded = [
  {
    title: "商品品种",
    key: "categoryCode",
    scopedSlots: { customRender: "categoryCode" },
    width: "33%"
  },
  {
    title: "跟进地区",
    key: "areas",
    scopedSlots: { customRender: "areas" },
    width: "33%"
  },
  {
    title: "操作",
    key: "handle",
    scopedSlots: { customRender: "handle" },
    width: "34%"
  }
];
const formDataStaff = [
  {
    label: "员工姓名",
    prop: "name",
    type: "text"
  },
  {
    label: "手机号码",
    prop: "phone",
    type: "text"
  },
  {
    label: "员工角色",
    prop: "roleId",
    type: "select",
    typeData: [],
    replaceFields: {
      label: "roleName",
      value: "id"
    }
  },
  {
    label: "有效期",
    prop: "validityType",
    type: "select",
    typeData: [],
    replaceFields: {
      label: "desc",
      value: "value"
    }
  }
];
const formDataBusiness = [
  {
    label: "跟进品种",
    prop: "categoryCode",
    slot: "categoryCode"
  },
  {
    label: "跟进地区",
    prop: "areas",
    slot: "areas"
  }
];

export default {
  components: {
    cAreas
  },
  data() {
    return {
      loading: false,
      columns: tableColumns,
      data: [],
      columnsExpanded: tableColumnsExpanded,
      visible: false,
      editRow: {},
      modalTitle: null,
      form: {
        roleId: null,
        validityType: null,
        categoryCode: null,
        areas: []
      },
      formData: null,
      submitLoading: false,
      rules: {
        categoryCode: [
          { required: true, message: "请选择品种", trigger: "change" }
        ],
        areas: [
          { required: true, message: "请选择跟进地区", trigger: "change" }
        ]
      },
      categoryOptions: [],
      categoryFilterList: []
    };
  },
  computed: {
    ...mapState(["user", "resource"]),
    // 是否已激活
    isActivated() {
      return row => {
        let res =
          [
            roleDict.unactivateuser.value,
            roleDict.unactivateadmin.value,
            roleDict.unactivatesuper.value
          ].indexOf(row.roleId) === -1;
        return res;
      };
    }
  },
  methods: {
    getBusinessCategory(userId) {
      getBusinessCategory({
        userId: userId
      }).then(res => {
        let data = res.concat(this.resource.categoryRootMenu);
        let tree = data.filter(i => i.children);
        for (let i = 0; i < data.length; i++) {
          tree.forEach(item => {
            if (
              data[i].categoryType &&
              data[i].categoryType === item.id &&
              this.filterList.indexOf(data[i].id) == -1
            ) {
              item.children.unshift(data[i]);
            }
          });
        }
      });
    },
    onExpanded({ expanded, record }) {
      if (expanded) {
        this.editRow.userId = record.userId;
      } else {
        this.editRow = {};
      }
    },
    validityType(val) {
      let res =
        val.validityType === 0 ? "永久" : this.$getTime(val.validityDate);
      return res;
    },
    // 编辑员工
    editStaff(row) {
      this.submitLoading = true;
      updateEmployee({
        preAuthId: row.preAuthId,
        userId: row.userId,
        roleId: this.form.roleId,
        validityType: this.form.validityType
      })
        .then(() => {
          this.$message.success("操作成功");
          this.visible = false;
          this.init();
        })
        .finally(() => {
          this.submitLoading = false;
        });
    },
    // 删除员工
    delStaff(row) {
      deleteEmployee({
        preAuthId: row.preAuthId
      }).then(() => {
        this.$message.success("操作成功");
        this.init();
      });
    },
    openEditDialog(row, type) {
      this.modalTitle =
        type === "0"
          ? "编辑业务跟进"
          : type === "1"
          ? "编辑员工"
          : "新增业务跟进";
      this.visible = true;
      this.editRow = Object.assign(this.editRow, row);
      this.formData = type === "1" ? formDataStaff : formDataBusiness;
      if (type === "0") {
        this.form.categoryCode = [row.categoryId];
        let areas = row.areas.split("").map(Number);
        this.form.areas = areas;
      } else if (type === "1") {
        this.form.name = row.userName;
        this.form.phone = row.phone;
        this.form.roleId = row.roleId;
        this.form.validityType = row.validityType;
        getRolesByCompany({
          companyId: this.user.company.id
        }).then(res => {
          formDataStaff[2].typeData = res;
        });
      } else if (type === "2") {
        this.categoryFilterList = row.companyUserLimitDBOS.map(
          item => item.categoryId
        );
        // 新增业务跟进默认选中全部地区
        let res = [];
        for (const key in area) {
          res.push(area[key].value);
        }
        this.form.areas = res;
      }
    },
    // 编辑业务
    editBusiness(row) {
      this.submitLoading = true;
      let areas = this.form.areas.join("");
      updateStaffLimit({
        id: row.id,
        userId: row.userId,
        categoryId: this.form.categoryCode[this.form.categoryCode.length - 1],
        areas: areas
      })
        .then(() => {
          this.visible = false;
          this.$message.success("操作成功");
          this.init();
        })
        .finally(() => {
          this.submitLoading = false;
        });
    },
    // 删除业务
    delBusiness(row) {
      delStaffLimit({
        id: row.id,
        userId: this.editRow.userId
      }).then(() => {
        this.$message.success("操作成功");
        this.init();
      });
    },
    // 新增业务跟进
    addBusiness(row) {
      this.submitLoading = true;
      let areas = this.form.areas.join("");
      addStaffLimit({
        userId: row.userId,
        categoryId: this.form.categoryCode[this.form.categoryCode.length - 1],
        areas: areas
      })
        .then(() => {
          this.$message.success("操作成功");
          this.visible = false;
          this.form.categoryCode = null;
          this.init();
        })
        .finally(() => {
          this.submitLoading = false;
        });
    },
    init() {
      this.loading = true;
      getUserManagementList()
        .then(res => {
          this.data = res;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    disposeAreas(data) {
      let areas = data.split("");
      let res = [];
      areas.forEach(item => {
        res.push(this.$getEnum(area, item));
      });
      return res;
    },
    modalOk() {
      this.$refs.form
        .validated()
        .then(() => {
          if (this.modalTitle === "编辑员工") {
            this.editStaff(this.editRow);
          } else if (this.modalTitle === "编辑业务跟进") {
            this.editBusiness(this.editRow);
          } else if (this.modalTitle === "新增业务跟进") {
            this.addBusiness(this.editRow);
          }
        })
        .catch(() => {});
    },
    modalCancel() {
      this.submitLoading = false;
      this.form = {
        roleId: null,
        validityType: null,
        categoryCode: null,
        areas: []
      };
    },
    formatValidityType() {
      formDataStaff[3].typeData = staff.validityType;
    },
    rowClassName(record) {
      if (!record.isOperateCompanyUserLimit) {
        return "no-expanded-row";
      }
    },
    isMySelf(userId) {
      return this.user.userData && this.user.userData.userId === userId;
    }
  },
  created() {
    this.init();
    this.formatValidityType();
  }
};
</script>

<style lang="scss" scoped>
::v-deep .no-expanded-row .ant-table-row-expand-icon-cell a {
  visibility: hidden;
}
</style>
